// import Axios from 'axios'
import Http from './http'

export function randomNum (m,n){
  return Math.floor(Math.random()*(m - n) + n);
}

export function getNotRepeatNum (start, end, count) {
  let diff = Math.abs(start - end)
  if (diff < count) {
    count = diff
  }

  let res = []
  while(res.length !== count) {
    let num = randomNum(start, end)
    if (!res.includes(num)) {
      res.push(num)
    }
  }
  return res
}

export function numberFormat (value) {
  let param = {}
  let k = 10000
  let sizes = ['', '万', '亿', '万亿']
  let i
  if(value < k){
      param.value = value
      param.unit = ''
  } else {
      i = Math.floor(Math.log(value) / Math.log(k))
      param.value = ((value / Math.pow(k, i))).toFixed(1)
      param.unit = sizes[i]
  }
  return `${param.value}${param.unit}`
}

export function downloadFile(url, fileName = '', requestConfig = { responseType: 'blob' }) {
  return Http.get(url, requestConfig)
    .then(resp => {
      if (resp.blob) {
        return resp.blob()
      } else if (resp.data) {
        return new Blob([resp.data])
      } else {
        return new Blob([resp])
      }
    })
    .then(blob => URL.createObjectURL(blob))
    .then(url => {
      downloadURL(url, fileName)
      URL.revokeObjectURL(url)
    })
}

function downloadURL(url, name = '') {
  const link = document.createElement('a')
  link.download = name
  link.href = url
  if ('download' in document.createElement('a')) {
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } else {
    // 对不支持download进行兼容
    click(link, (link.target = '_blank'))
  }
}

// clone https://github.com/eligrey/FileSaver.js/blob/master/src/FileSaver.js
function click(node) {
  try {
    node.dispatchEvent(new MouseEvent('click'))
  } catch (e) {
    var evt = document.createEvent('MouseEvents')
    evt.initMouseEvent(
      'click',
      true,
      true,
      window,
      0,
      0,
      0,
      80,
      20,
      false,
      false,
      false,
      false,
      0,
      null
    )
    node.dispatchEvent(evt)
  }
}

export function rangs(num, max, min) {
  return Math.max(min, Math.min(num, max))
}

export function addZore(num) {
  return num < 10 ? `0${num}` : num
}

export function shuffle(arr) {
  let _arr = arr.slice()
  for (let i = 0; i < _arr.length; i++) {
    let j = randomNum(0, i)
    let t = _arr[i]
    _arr[i] = _arr[j]
    _arr[j] = t
  }
  return _arr
}
